#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of KeyExtracta
# <http://code.google.com/p/keyextracta/>.
#
# KeyExtracta is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# KeyExtracta is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with KeyExtracta.  If not, see <http://www.gnu.org/licenses/>.

import _winreg as wr
import collections, time
from core import regutils

def formatKeyValue(value):
  """Format the key value for output"""
  val = value[0].lstrip('x9392') # Strip 'x9392' from EA keys
  if len(val) is 20:
    val = '-'.join(list(regutils.chunks(val,4)))
  # Format Command and Conquer key as XXXX-XXXXXXX-XXXXXXX-XXXX
  elif len(val) is 22:
    prefix = '0'*3
    val = '-'.join(list(regutils.chunks(''.join([prefix,val]),7)))[len(prefix):]
  # Format Call of Juarez key as XXX-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
  elif len(val) is 28:
    prefix = '0'*2
    val = '-'.join(list(regutils.chunks(''.join([prefix,val]),5)))[len(prefix):]
  # Format dates
  if value[1] is 4 and 'date' in d['name'].lower():
    val = time.strftime("%m/%d/%y", time.gmtime(val))
  return val

def getDict(a, flag=wr.KEY_WOW64_32KEY):
  """Return dictionary with properties from fed line from config.cfg"""
  l = []
  for idx, s in enumerate(a.split('|')):
    if idx > 0:
      name, path, key = s.split('=')
      root, path = path.split('\\', 1)
      d = {
        'name': name.rstrip('\n\\'), 'root': root.rstrip('\n\\'),
        'path': path.rstrip('\n\\'), 'key': key.rstrip('\n\\')
      }
      l.append(d)
    else:
      l.append(s)

  dict = collections.OrderedDict([])
  for idx, d in enumerate(l):
    if idx is 0:
      dict['Name:'] = d.lstrip()
    if idx > 0:
      try:
        reg_root = wr.OpenKey(getattr(wr, d['root']), d['path'], 0,
          wr.KEY_READ | flag)
        value = wr.QueryValueEx(reg_root, d['key'])
      except:
        continue
      dict['%s:' % d['name']] = formatKeyValue(value)
  if len(dict) > 1:
    return dict
  else:
    return None
  
def getKeys():
  """Get all thrid part app keys"""
  l = []
  fl = regutils.getOSFlagList()
  for flag in fl:
    for file in ['config.cfg','custom.cfg']:
      try:
        with open(file, 'r') as f:
          for a in f:
            if a.lstrip().startswith(';'): # If entry is commented out
              continue
            try:
              d = getDict(a, flag)
            except:
              continue
            if d is not None:
              l.append(d)
      except:
        pass 
  if len(l) is 0:
    l = None
  return l
  